# -*- coding: utf-8 -*-
import os

from django.http import HttpResponse
from django.shortcuts import render_to_response
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.reverse import reverse
import serializers
import interface
import json


class StrategyNew(APIView):
    @staticmethod
    def post(request):
        try:
            # print request.data
            result = interface.new_strategy(request.data, request.session)
            return Response(result)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyDelete(APIView):
    @staticmethod
    def post(request):
        try:
            # print request.data
            state = interface.del_strategy(request)
            return Response({"state": state})
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyListView(APIView):
    @staticmethod
    def post(request):
        try:
            queryset = interface.get_strategy_list(request.data, request.session)
            return Response(queryset)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategySaveView(APIView):
    @staticmethod
    def post(request):
        try:
            # print request.data
            state = interface.save_strategy(request.data, request.session)
            return Response({"state": state})
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyBacktestView(APIView):
    @staticmethod
    def post(request):
        try:
            json_str = interface.exec_strategy(request.data, request.session)
            return Response(json_str)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyInfoView(APIView):
    @staticmethod
    def post(request):
        try:
            my_query_set = interface.get_strategy_info(request.data, request.session)
            serializer = serializers.StrategyInfoSerializer(my_query_set)
            return Response(serializer.data)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class ReturnInfoView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_return_info(request.data, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class TradeDetailView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list, transaction, buy_vol, sell_vol = interface.get_trade_detail(request.data, request.session)
            kline = interface.get_kline_data()
            return Response({'buySellPointList': return_list, 'klineDataList': kline,
                             'transaction': transaction, 'buy_vol': buy_vol, 'sell_vol': sell_vol})
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class DailyPositionView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_position_detail(request.data, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class OutputLogView(APIView):
    @staticmethod
    def post(request):
        try:
            return Response(interface.output_log(request.data, request.session))
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyReturnView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 1, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyAlphaView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 4, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyBetaView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 5, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategySharpView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 6, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategySortinoView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 7, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyInfoRatioView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 8, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyVolatilityView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 9, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyMaxDrewdownView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_detail(request.data, 10, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class StrategyCopyView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.copy_strategy(request.data, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class BackTestHistoryView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_back_test_history(request.data, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class HistoryCodeView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_code(request.data, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


class HistoryResultView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = interface.get_history_result(request.data, request.session)
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


# 处理git提交数据
class GitView(APIView):
    @staticmethod
    def post(request):
        try:
            return_list = {'state': 0}
            # print 'code has update ...'
            # 切换目录
            os.chdir('/home/dcr/workspace/dQuant/')
            # 拉去新更新
            os.system('git pull')
            print 'code update finish ...'
            return Response(return_list)
        except Exception, e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def api_root(request, format=None):
    return Response({
        'strategycopy': reverse('strategycopy', request=request, format=format),
        'strategynew': reverse('strategynew', request=request, format=format),
        'strategydelete': reverse('strategydelete', request=request, format=format),
        'strategylist': reverse('strategylist', request=request, format=format),
        'strategybacktest': reverse('strategybacktest', request=request, format=format),
        'strategysave': reverse('strategysave', request=request, format=format),
        'strategyinfo': reverse('strategyinfo', request=request, format=format),
        'returninfo': reverse('returninfo', request=request, format=format),
        'tradedetail': reverse('tradedetail', request=request, format=format),
        'dailyposition': reverse('dailyposition', request=request, format=format),
        'outputlog': reverse('outputlog', request=request, format=format),
        'strategyreturn': reverse('strategyreturn', request=request, format=format),
        'strategyalpha': reverse('strategyalpha', request=request, format=format),
        'strategybeta': reverse('strategybeta', request=request, format=format),
        'strategysharp': reverse('strategysharp', request=request, format=format),
        'strategysortino': reverse('strategysortino', request=request, format=format),
        'strategyinforatio': reverse('strategyinforatio', request=request, format=format),
        'strategyvolatility': reverse('strategyvolatility', request=request, format=format),
        'strategymaxdrewdown': reverse('strategymaxdrewdown', request=request, format=format),
        'backtesthistory': reverse('backtesthistory', request=request, format=format),
        'historycode': reverse('historycode', request=request, format=format),
        'historyresult': reverse('historyresult', request=request, format=format),
        'push_cb': reverse('push_cb', request=request, format=format),
    })


def index(request):
    if request.method == 'POST':
        if 'start_date' in request.POST:
            codes_source = request.POST['source_code']
            start_date = request.POST['start_date']
            end_date = request.POST['end_date']
            cash = request.POST['cash']
            session_info = {"userid": "daichaoren", "strategyid": "00001", "versionid": "0001"}
            # print start_date, end_date, cash
            info = {}
            info = interface.helloQuant(codes_source, start_date, end_date, int(cash), session_info)
            totalinfo = info['totalinfo']
            if totalinfo != []:
                total_returns_list = info['total_returns']
                benchmark_return_list = info['benchmarkReturn']
                result = {
                    'totalreturn': round(totalinfo.totalreturn, 4),
                    'benchmark': round(totalinfo.benchmark, 4),
                    'annualized_returns': round(totalinfo.runtime, 4),
                    'total_returns_list': total_returns_list,
                    'benchmark_return_list': benchmark_return_list,
                    'errlog': info['errlog'],
                    'errtype': info['errtype']
                }
                json_str = json.dumps(result)
                #                 print (json_str)
                return HttpResponse(json_str, content_type="application/json")
            else:
                result = {
                    'totalreturn': 0,
                    'benchmark': 0,
                    'annualized_returns': 0,
                    'total_returns_list': [],
                    'benchmark_return_list': [],
                    'errlog': info['errlog'],
                    'errtype': info['errtype']
                }
                json_str = json.dumps(result)
                return HttpResponse(json_str, content_type="application/json")
        elif 'source_code' in request.POST:
            codes_source = request.POST['source_code']
            return HttpResponse("")
        else:
            return HttpResponse("")
    else:
        return render_to_response('UPQuant/index.html')
